package com.butterfly.encrypt.util;

import java.io.UnsupportedEncodingException;

import org.apache.log4j.Logger;


/**
 * Base64 加解密相关 工具类(本工具类是标准的base64加密，没有对"+,/,=" 做处理
 * 		     不是URL的改进Base64编码并不适合直接放在URL里传输)
 * @author fox email:hitman__47@163.com
 * @version 1.0 2013-10-3
 * 
 * 描 述：
 * 		1 Base64 目的：
 * 				1.1具有不可读性，即所编码的数据不会被人用肉眼所直接看到
 * 				1.2编码比较简短,传输速度非常快。
 * 				1.3 可用于在HTTP环境下传递较长的标识信息。
 * 				1.4将二进制序列转换为人类可读的ASCII字符序列，常用在需用通过文本来传输二进制数据的协议中，如HTTP和SMTP等
 * 				1.5Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一。
 * 		2 Base64 原理:
 * 			Base64要求把每三个8Bit的字节转换为四个6Bit的字节（3*8 = 4*6 = 24），然后把6Bit再添两位高位0，组成四个8Bit的字节，也就是说，转换后的字符串理论上将要比原来的长1/3。
 * 			步骤：2.1对于待编码数据，以3个字节为单位，依次取6位，前两位补0形成8位编码，由于3×8=4×6，3个字节的输入会编码成4个字节的输出。
 * 				  2.2如果剩下的字符不足3个字节，则用0填充，输出字符使用“=”，因此编码后输出的文本末尾可能会出现1个或2个“=”。
 * 				  2.3 每76个字符加一个换行符.
 * 				  2.4最后的结束符也要处理
 *         因此，Base 64解码过程与编码过程正好相反。
 * 				  
 */
public class Base64 {
	private static final int BASELENGTH = 255;
	private static final int LOOKUPLENGTH = 64;
	private static final int TWENTYFOURBITGROUP = 24;
	private static final int EIGHTBIT = 8;
	private static final int SIXTEENBIT = 16;
	private static final int FOURBYTE = 4;
	private static final int SIGN = -128;
	private static final byte PAD = (byte) '=';
	private static byte[] base64Alphabet = new byte[BASELENGTH];
	private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
	private static final  Logger log = Logger.getLogger(Base64.class);

	static {
		for (int i = 0; i < BASELENGTH; i++) {
			base64Alphabet[i] = -1;
		}
		for (int i = 'Z'; i >= 'A'; i--) {
			base64Alphabet[i] = (byte) (i - 'A');
		}
		for (int i = 'z'; i >= 'a'; i--) {
			base64Alphabet[i] = (byte) (i - 'a' + 26);
		}
		for (int i = '9'; i >= '0'; i--) {
			base64Alphabet[i] = (byte) (i - '0' + 52);
		}

		base64Alphabet['+'] = 62;
		base64Alphabet['/'] = 63;

		for (int i = 0; i <= 25; i++)
			lookUpBase64Alphabet[i] = (byte) ('A' + i);

		for (int i = 26, j = 0; i <= 51; i++, j++)
			lookUpBase64Alphabet[i] = (byte) ('a' + j);

		for (int i = 52, j = 0; i <= 61; i++, j++)
			lookUpBase64Alphabet[i] = (byte) ('0' + j);

		lookUpBase64Alphabet[62] = (byte) '+';
		lookUpBase64Alphabet[63] = (byte) '/';
	}

	public static boolean isBase64(String isValidString) {
		return isArrayByteBase64(isValidString.getBytes());
	}
	/**
	 * 判断数据是否是base64格式
	 * @param octect
	 * @return boolean
	 */
	public static boolean isBase64(byte octect) {
		// shall we ignore white space? JEFF??
		return (octect == PAD || base64Alphabet[octect] != -1);
	}

	public static boolean isArrayByteBase64(byte[] arrayOctect) {
		int length = arrayOctect.length;
		if (length == 0) {
			// shouldn't a 0 length array be valid base64 data?
			// return false;
			return true;
		}
		for (int i = 0; i < length; i++) {
			if (!Base64.isBase64(arrayOctect[i]))
				return false;
		}
		return true;
	}
	/**
	 * 数据加密 成base64格式
	 * 
	 * @param data
	 *            需要base64编码的字符串
	 * @return 经过base64编码的字符串.
	 */
	
	public static String encodeByString(String data) {
		if(data==null)
			data="";
		try {
			return new String(encode(data.getBytes("UTF-8")));
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage(),e);
			return "";
		}
	}
	
	/**
	 * 数据加密 成base64格式
	 * 
	 * @param 2进制byte数组
	 *            Array containing binary data to encode.
	 * @return base64编码的2进制数组.
	 */
	public static byte[] encode(byte[] binaryData) {
		int lengthDataBits = binaryData.length * EIGHTBIT;
		int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
		int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
		byte[] encodedData = null;

		if (fewerThan24bits != 0) {
			// data not divisible by 24 bit
			encodedData = new byte[(numberTriplets + 1) * 4];
		} else {
			// 16 or 8 bit
			encodedData = new byte[numberTriplets * 4];
		}

		byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;

		int encodedIndex = 0;
		int dataIndex = 0;
		int i = 0;
		for (i = 0; i < numberTriplets; i++) {
			dataIndex = i * 3;
			b1 = binaryData[dataIndex];
			b2 = binaryData[dataIndex + 1];
			b3 = binaryData[dataIndex + 2];

			l = (byte) (b2 & 0x0f);
			k = (byte) (b1 & 0x03);

			encodedIndex = i * 4;
			byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
			byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
			byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);

			encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
			encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)];
			encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3];
			encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];
		}

		// form integral number of 6-bit groups
		dataIndex = i * 3;
		encodedIndex = i * 4;
		if (fewerThan24bits == EIGHTBIT) {
			b1 = binaryData[dataIndex];
			k = (byte) (b1 & 0x03);
			byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
			encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
			encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
			encodedData[encodedIndex + 2] = PAD;
			encodedData[encodedIndex + 3] = PAD;
		} else if (fewerThan24bits == SIXTEENBIT) {

			b1 = binaryData[dataIndex];
			b2 = binaryData[dataIndex + 1];
			l = (byte) (b2 & 0x0f);
			k = (byte) (b1 & 0x03);

			byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
			byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);

			encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
			encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)];
			encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
			encodedData[encodedIndex + 3] = PAD;
		}

		return encodedData;
	}
	/**
	 * base64解码
	 * @param base64Data
	 * 						经过base64编码的字符串
	 * @return 解码后的字符串
	 */
	public static String decodeByString(String base64Data){
		if(base64Data == null)
			return "";
		try {
			return new String (decode(base64Data.getBytes("UTF-8")));
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage(),e);
			return "";
		}
		
	}
	/**
	 * base64解码
	 * @param base64Data
	 * 						经过base64编码的字符串
	 * @return 解码后的字符串
	 */
	public static byte[] decodeByteByString(String base64Data){
		if(base64Data == null)
			return new byte[0];
		try {
			return decode(base64Data.trim().getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage(),e);
			return decode(base64Data.trim().getBytes());
		}
		
	}

	/**
	 * 解码base64 数据
	 * 
	 * @param base64Data
	 *            base64 编码过的字节数组
	 * @return 解码后的字节数组
	 */
	public static byte[] decode(byte[] base64Data) {
		// handle the edge case, so we don't have to worry about it later
		if (base64Data.length == 0) {
			return new byte[0];
		}

		int numberQuadruple = base64Data.length / FOURBYTE;
		byte[] decodedData = null;
		byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;

		// Throw away anything not in base64Data

		int encodedIndex = 0;
		int dataIndex = 0;
		{
			// this sizes the output array properly - rlw
			int lastData = base64Data.length;
			// ignore the '=' padding
			while (base64Data[lastData - 1] == PAD) {
				if (--lastData == 0) {
					return new byte[0];
				}
			}
			decodedData = new byte[lastData - numberQuadruple];
		}

		for (int i = 0; i < numberQuadruple; i++) {
			dataIndex = i * 4;
			marker0 = base64Data[dataIndex + 2];
			marker1 = base64Data[dataIndex + 3];

			b1 = base64Alphabet[base64Data[dataIndex]];
			b2 = base64Alphabet[base64Data[dataIndex + 1]];

			if (marker0 != PAD && marker1 != PAD) {
				// No PAD e.g 3cQl
				b3 = base64Alphabet[marker0];
				b4 = base64Alphabet[marker1];

				decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
				decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
				decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
			} else if (marker0 == PAD) {
				// Two PAD e.g. 3c[Pad][Pad]
				decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
			} else if (marker1 == PAD) {
				// One PAD e.g. 3cQ[Pad]
				b3 = base64Alphabet[marker0];

				decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
				decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
			}
			encodedIndex += 3;
		}
		return decodedData;
	}

	public static void main(String args[]) throws UnsupportedEncodingException {
//		String aaa = "6K+356S6X+adqOWpt18yMDEyLTEwLTIy";
//		System.out.println(new String(Base64.decode(aaa.getBytes())));
//
//		String aa = "MTExMQ==";
//		System.out.println(new String((Base64.decode(aa.getBytes()))));
//		
//		String deCode = "RklMRTUwNTI4NDU5NjI4U1QwTy5kb2M=;";
//		System.out.println("deCode"+new String((Base64.decode(deCode.getBytes()))));
		System.out.println("-----"+new String(Base64.decode("56ysMuacn+aAu+WKnuS8muiuru+8iDA2LzA277yJ".getBytes()),"utf-8"));
		System.out.println("-----"+decodeByString("ICA="));
		System.out.println("-----"+new String(Base64.encode("  ".getBytes())));
		System.out.println("-----"+encodeByString("  "));
	}
		
}
